package com.googlecode.cpbi;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.osgi.framework.Constants;

import com.googlecode.cpbi.util.BundleManifest;
import com.googlecode.cpbi.util.Osgi;

public class ExportBundleInstaller {

	private final Osgi osgi;

	public ExportBundleInstaller(Osgi osgiImplementation) {
		osgi = osgiImplementation;
	}

	public void installSystemBundleFragmentExporting(Map exportedAndUsedPackages) {
		exportedAndUsedPackages.remove("");
		BundleManifest manifest = new BundleManifest();
		String symbolicName = getClass().getPackage().getName() + ".export";
		manifest.setSymbolicName(symbolicName);
		manifest.setFragmentHost(Constants.SYSTEM_BUNDLE_SYMBOLICNAME);
		manifest.setExportPackage(getExportPackageHeaderValueOf(exportedAndUsedPackages));
		osgi.installEmptyBundleAround(manifest.getManifest(), "bundle:" + symbolicName);
	}

	private String getExportPackageHeaderValueOf(Map exportedAndUsedPackages) {
		StringBuffer exportPackageValue = new StringBuffer();
		Set exportedPackages = exportedAndUsedPackages.keySet();
		int index = 0;
		for (Iterator iterator = exportedPackages.iterator(); iterator.hasNext();) {
			String exportedPackage = (String) iterator.next();
			exportPackageValue.append(exportedPackage);
			append((Set) exportedAndUsedPackages.get(exportedPackage), exportPackageValue);
			if (++index < exportedPackages.size()) exportPackageValue.append(Osgi.PACKAGE_DELIMITER);
		}
		return exportPackageValue.toString();
	}

	private void append(Set usedPackages, StringBuffer exportPackageValue) {
		if (!usedPackages.isEmpty()) {
			exportPackageValue.append(Osgi.ATTRIBUTE_DELIMITER).append("uses:=\"");
			int index = 0;
			for (Iterator iterator = usedPackages.iterator(); iterator.hasNext();) {
				exportPackageValue.append((String) iterator.next());
				if (++index < usedPackages.size()) exportPackageValue.append(Osgi.PACKAGE_DELIMITER);
			}
			exportPackageValue.append('"');
		}
	}

}
